package com.lin.servlet;

import java.io.IOException;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lin.service.IOrderService;
import com.lin.service.OrderServiceImpl;
import com.lin.utils.BaseServlet;
import com.lin.utils.PaymentUtil;
import com.lin.utils.UUIDUtils;
import com.lin.vo.Cart;
import com.lin.vo.CartItem;
import com.lin.vo.Order;
import com.lin.vo.OrderItem;
import com.lin.vo.User;
/**
 *  Order(订单控制器)
 * @author manage
 *
 */
@WebServlet(name="OrderServlet",urlPatterns={"/orderServlet"})
public class OrderServlet  extends BaseServlet{
	
	private static final long serialVersionUID = 1L;
	private IOrderService orderService = new OrderServiceImpl();

	public String saveOrder(HttpServletRequest request,HttpServletResponse response){
		/**
		 * 1.封装订单数据t 
		 */
		Order order=new Order();
		order.setOid(UUIDUtils.getUUID()); // 设置订单编号
		order.setState(1);                 // 设置订单状态
		order.setOrdertime(new Date());    // 设置下单时间
		order.setAddress(null);			   // 设置收货地址
		
		/**
		 * 2.从购物车中获取总金额数目(session域中)
		 */
		Cart cart = (Cart) request.getSession().getAttribute("cart");
		if(cart == null){
			request.setAttribute("msg", "亲！您还没有购物，不能产生订单~");
			return "change:/jsps/msg.jsp";
		}
		order.setTotal(cart.getTotal());
		/**
		 * 3.从登陆的session域中获取登录的User
		 */
		User user =(User) request.getSession().getAttribute("exitUser");
		if(user == null){
			request.setAttribute("msg", "亲,你还没有登陆捏~");
			return "change:/jsps/user/login.jsp";
		}
		order.setUser(user);
		/**
		 * 4.封装订单项信息(从购物车中获得购物项，然后将购物项封装到订单相中)
		 */
		Collection<CartItem> cartItems = cart.getCartItem();
		for(CartItem cartItem :cartItems){
			OrderItem orderItem =new OrderItem();
			orderItem.setItemid(UUIDUtils.getUUID());
			orderItem.setCount(cartItem.getCount());
			orderItem.setSubtotal(cartItem.getSubtotal());
			orderItem.setBook(cartItem.getBook());   
			orderItem.setOrder(order); // 订单项关联订单
		
			// 将封装号的订单项保存到订单的集合中
			order.getOrderItems().add(orderItem);
		}
		/**
		 * 5.调用service层方法
		 */
		orderService.sava(order);
	 	/**
	 	 * 6.清空购物车
	 	 */
		cart.clearCart();
		/**
		 * 7.保存数据跳转
		 */
		request.setAttribute("order", order);
		
		return "change:/jsps/order/desc.jsp";
	}
	/**
	 * 根据Uid查询我的订单信息
	 * @return
	 */
	public String findByUid(HttpServletRequest request,HttpServletResponse response){
		/**
		 * 1.从Session域中获取用户登陆信息
		 */
		User user = (User) request.getSession().getAttribute("exitUser");
		/**
		 * 2.调用业务层方法 
		 */
		List<Order> orderLists=orderService.findByUid(user);
		/**
		 * 3.保存域中跳转
		 */
		request.setAttribute("orderLists", orderLists);
		return "change:/jsps/order/list.jsp";
	}
	/**
	 * 根据订单id查询订单信息
	 * @param request
	 * @param response
	 * @return
	 */
	public String findByOid(HttpServletRequest request,HttpServletResponse response){
		/**
		 * 1.获取订单id
		 */
		String oid = request.getParameter("oid");
		/**
		 * 2.调用业务层方法
		 */
		Order order=orderService.findByOid(oid);
		/**
		 * 3.保存到域中
		 */
		request.setAttribute("order", order);
		return "change:/jsps/order/list.jsp";
	}
	
	public String paymentOrder(HttpServletRequest request,HttpServletResponse response) throws IOException{
		// 1.获取参数
		String oid = request.getParameter("oid");
		String address = request.getParameter("address");
		// 将用户的送货地址插入到数据库中
		// 面向对象的思想，定义一个方法，传入订单对象
		// 通过前台页面穿进来的订单号，来得到订单对象
		Order order = orderService.findByOid(oid);
		order.setAddress(address);
		orderService.updateOrder(order);
		// 支付通道编码
		String pd_FrpId = request.getParameter("pd_FrpId");

		// 2.操作易宝支付接口
		// 组装参数
		String p0_Cmd = "Buy"; // 业务类型
		String p1_MerId = "10001126856"; // 商户编号
		String p2_Order = oid; // 商户订单号码
		String p3_Amt = "0.01"; // 支付金额
		String p4_Cur = "CNY"; // 支付币种
		String p5_Pid = ""; // 商品名称
		String p6_Pcat = ""; // 商品种类
		String p7_Pdesc = ""; // 商品描述
		String p8_Url = "http://localhost/estore/orderServlet?method=callBack"; // 商户接收支付成功数据的地址
		String p9_SAF = ""; // 送货地址
		String pa_MP = ""; // 商户扩展信息
		String pr_NeedResponse = "1"; // 应答机制
		// 密钥
		String keyValue = "69cl522AV6q613Ii4W6u8K6XuW8vM1N6bFgyv769220IuYe9u37N4y7rI4Pl";
		String hmac = PaymentUtil.buildHmac(p0_Cmd, p1_MerId, p2_Order, p3_Amt, p4_Cur, p5_Pid, p6_Pcat, p7_Pdesc,
				p8_Url, p9_SAF, pa_MP, pd_FrpId, pr_NeedResponse, keyValue); // 数字签名

		// 重定向：准备工作
		StringBuffer buffer = new StringBuffer("https://www.yeepay.com/app-merchant-proxy/node?");
		buffer.append("p0_Cmd=").append(p0_Cmd).append("&");
		buffer.append("p1_MerId=").append(p1_MerId).append("&");
		buffer.append("p2_Order=").append(p2_Order).append("&");
		buffer.append("p3_Amt=").append(p3_Amt).append("&");
		buffer.append("p4_Cur=").append(p4_Cur).append("&");
		buffer.append("p5_Pid=").append(p5_Pid).append("&");
		buffer.append("p6_Pcat=").append(p6_Pcat).append("&");
		buffer.append("p7_Pdesc=").append(p7_Pdesc).append("&");
		buffer.append("p8_Url=").append(p8_Url).append("&");
		buffer.append("p9_SAF=").append(p9_SAF).append("&");
		buffer.append("pa_MP=").append(pa_MP).append("&");
		buffer.append("pd_FrpId=").append(pd_FrpId).append("&");
		buffer.append("pr_NeedResponse=").append(pr_NeedResponse).append("&");
		buffer.append("keyValue=").append(keyValue).append("&");
		buffer.append("hmac=").append(hmac);
		// 准备完毕，发出重定向
		response.sendRedirect(buffer.toString());
		return null;
	}
	/**
	 * 从请求中获取响应数据
	 * @param request
	 * @param response
	 * @return
	 */
	public String callBack(HttpServletRequest request,HttpServletResponse response){
		// 从请求中响应回数据
		String p1_MerId = request.getParameter("p1_MerId");
		String r0_Cmd = request.getParameter("r0_Cmd");
		String r1_Code = request.getParameter("r1_Code");
		String r2_TrxId = request.getParameter("r2_TrxId");
		String r3_Amt = request.getParameter("r3_Amt");
		String r4_Cur = request.getParameter("r4_Cur");
		String r5_Pid = request.getParameter("r5_Pid");
		String r6_Order = request.getParameter("r6_Order");
		String r7_Uid = request.getParameter("r7_Uid");
		String r8_MP = request.getParameter("r8_MP");
		String r9_BType = request.getParameter("r9_BType");
		String keyValue = "69cl522AV6q613Ii4W6u8K6XuW8vM1N6bFgyv769220IuYe9u37N4y7rI4Pl";
		// 数字签名，也是响应回当前站点
		String hmac = request.getParameter("hmac");
		boolean flag = PaymentUtil.verifyCallback(hmac, p1_MerId, r0_Cmd, r1_Code, r2_TrxId, r3_Amt, r4_Cur, r5_Pid, r6_Order, r7_Uid, r8_MP, r9_BType, keyValue);
		// 当支付乘公共，会返回true，此时需要现将订单中的状态修改为2   即：付款成功等待发货
		if (flag) {
	
			Order order = orderService.findByOid(r6_Order);
			order.setState(2);
			orderService.updateOrder(order);
		}
		request.setAttribute("msg", "您已经为订单号：" + r6_Order + " 付款成功，付款金额为： " + r3_Amt + " 元");
		System.out.println(3);
		return "change:/jsps/msg.jsp";
	}

}
